package com.example.sbeducation.utils;

import com.example.sbeducation.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传工具类
 */
@Slf4j
@Component
public class FileUtil {

  @Value("${file.upload-dir}")
  private String uploadDir;

  /**
   * 上传文件
   * 
   * @param file 文件
   * @param type 文件类型
   * @return 文件相对路径
   */
  public String uploadFile(MultipartFile file, String type) {
    if (file.isEmpty()) {
      throw new BusinessException(400, "文件为空");
    }

    // 获取原始文件名
    String originalFilename = file.getOriginalFilename();
    log.info("开始上传文件: {}, 类型: {}, 大小: {}", originalFilename, type, file.getSize());

    // 获取文件后缀
    String suffix = "";
    if (originalFilename != null && originalFilename.contains(".")) {
      suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    // 生成新文件名
    String newFilename = UUID.randomUUID().toString().replace("-", "") + suffix;

    // 按日期生成目录结构
    String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

    // 使用File对象处理路径
    File uploadRoot = new File(uploadDir);
    log.info("上传根目录: {}", uploadRoot.getAbsolutePath());

    // 确保上传根目录存在
    if (!uploadRoot.exists()) {
      log.info("创建上传根目录: {}", uploadRoot.getAbsolutePath());
      if (!uploadRoot.mkdirs()) {
        log.error("创建上传根目录失败: {}", uploadRoot.getAbsolutePath());
        throw new BusinessException(500, "创建上传根目录失败");
      }
    }

    // 类型目录
    File typeDir = new File(uploadRoot, type);
    if (!typeDir.exists()) {
      log.info("创建类型目录: {}", typeDir.getAbsolutePath());
      if (!typeDir.mkdirs()) {
        log.error("创建类型目录失败: {}", typeDir.getAbsolutePath());
        throw new BusinessException(500, "创建类型目录失败");
      }
    }

    // 日期目录 (yyyy/MM/dd)
    String[] datePathParts = datePath.split("/");
    File yearDir = new File(typeDir, datePathParts[0]);
    File monthDir = new File(yearDir, datePathParts[1]);
    File dayDir = new File(monthDir, datePathParts[2]);

    if (!dayDir.exists()) {
      log.info("创建日期目录: {}", dayDir.getAbsolutePath());
      if (!dayDir.mkdirs()) {
        log.error("创建日期目录失败: {}", dayDir.getAbsolutePath());
        throw new BusinessException(500, "创建日期目录失败");
      }
    }

    // 保存文件
    File dest = new File(dayDir, newFilename);
    try {
      log.info("保存文件到: {}", dest.getAbsolutePath());
      file.transferTo(dest);
      String fileUrl = "/" + type + "/" + datePath + "/" + newFilename;
      log.info("文件上传成功: {}, URL: {}", dest.getAbsolutePath(), fileUrl);
      return fileUrl;
    } catch (IOException e) {
      log.error("文件上传失败: {}", e.getMessage(), e);
      throw new BusinessException(500, "文件上传失败: " + e.getMessage());
    }
  }

  /**
   * 删除文件
   * 
   * @param filePath 文件相对路径
   * @return 是否删除成功
   */
  public boolean deleteFile(String filePath) {
    if (filePath == null || filePath.trim().isEmpty()) {
      return false;
    }

    // 移除开头的斜杠
    if (filePath.startsWith("/")) {
      filePath = filePath.substring(1);
    }

    // 使用File对象处理路径
    File uploadRoot = new File(uploadDir);
    File fileToDelete = new File(uploadRoot, filePath);
    log.info("尝试删除文件: {}, 文件是否存在: {}", fileToDelete.getAbsolutePath(), fileToDelete.exists());

    if (fileToDelete.exists() && fileToDelete.isFile()) {
      if (fileToDelete.delete()) {
        log.info("文件删除成功：{}", fileToDelete.getAbsolutePath());
        return true;
      } else {
        log.error("文件删除失败：{}", fileToDelete.getAbsolutePath());
        return false;
      }
    }
    return false;
  }
}